<?php

namespace plugin\admin\app\service\v1;

use plugin\admin\app\common\fast\Date;
use plugin\admin\app\common\Util;
use plugin\admin\app\constant\v1\CommonConstant;
use plugin\admin\app\model\Admin;
use plugin\admin\app\model\AdminRole;
use plugin\admin\app\model\V1UserExtend;
use plugin\admin\app\model\V1UserMoneyLog;
use plugin\admin\app\model\V1UserCommissionLog;
use support\exception\BusinessException;

/**
 * 会员服务类
 **/
class UserService
{

    /**
     * 添加会员
     *
     * @param array $params
     * @param integer $sms_check 验证码验证:0=不验证,1=验证
     **/
    public static function registerUser($params, $sms_check)
    {
        list($username, $password, $password_confirm, $qq, $weixin, $mobile, $code, $invitation, $link_id) = array_values($params);

        $username_check = Admin::where('username', $username)->value('id');
        if ($username_check) {
            throw new BusinessException('用户名已存在!');
        }

        $mobile_check = Admin::where('mobile', $mobile)->whereIn('user_status', [CommonConstant::DEFAULT_2])->value('id');
        if ($mobile_check) {
            throw new BusinessException('手机号已存在!');
        }

        if ($sms_check == CommonConstant::DEFAULT_1) {
            $sms_res = SmsService::check($mobile, $code, 'register_user');
            if (!$sms_res) {
                throw new BusinessException('验证码错误!');
            }
        }

        list($invitation_info, $extend_data) = UserExtendService::getUserExtendData($invitation, $link_id);

        $password = Util::passwordHash($password);
        $data = [];
        $data['username'] = $username;
        $data['nickname'] = $username;
        $data['password'] = $password;
        $data['avatar'] = CommonConstant::AVATAR;
        $data['mobile'] = $mobile;
        $data['status'] = CommonConstant::DEFAULT_0;
        $data['password_new'] = $password_confirm;
        $data['user_status'] = CommonConstant::DEFAULT_2;
        $data['invitation_id'] = $invitation_info ? $invitation_info['id'] : 0;
        $data['invitation'] = $invitation_info ? $invitation : '';
        $data['qq'] = $qq;
        $data['weixin'] = $weixin;
        Util::db()->transaction(function () use ($data, $extend_data) {
            $admin_id = doInsert($data, new Admin());
            $admin_role['admin_id'] = $admin_id;
            $admin_role['role_id'] = $data['user_status'];
            doInsert($admin_role, new AdminRole());
            $extend_data = array_map(function ($item) use ($admin_id) {
                $item['user_id'] = $admin_id;
                return $item;
            }, $extend_data);
            V1UserExtend::insert($extend_data);
        });
//        Db::beginTransaction();
//        try {
//            $admin_id = doInsert($data, new Admin());
//            $admin_role = new AdminRole();
//            $admin_role->admin_id = $admin_id;
//            $admin_role->role_id = $data['user_status'];
//            $admin_role->save();
//            Db::commit();
//        } catch (BusinessException $e) {
//            Db::rollback();
//            throw new BusinessException('File：' . $e->getFile() . " ，Line：" . $e->getLine() . '，Message：' . $e->getMessage());
//        }
        return true;
    }

    /**
     * 重置密码
     *
     * @param array $params
     **/
    public static function forgetUser($params)
    {
        list($mobile, $code, $password) = array_values($params);

        $mobile_check = Admin::where('mobile', $mobile)->whereIn('user_status', [CommonConstant::DEFAULT_2])->first('id');
        if (!$mobile_check) {
            throw new BusinessException('手机号不存在!');
        }

        $sms_res = SmsService::check($mobile, $code, 'forget_user');
        if (!$sms_res) {
            throw new BusinessException('验证码错误!');
        }

        $password = Util::passwordHash($password);
        $mobile_check->password = $password;
        $mobile_check->save();
        return true;
    }


    /**
     * 首页信息
     *
     * @param array $admin
     **/
    public static function getIndex($admin)
    {
        // 上级信息
        $parent_user_info = self::getParentUserInfo($admin);

        // 获取会员推广权限
        list($line_list, $line_column) = LineService::select();
        $user_extend = UserExtendService::getUserExtend($line_column, $admin);
        $user_extend = UserExtendService::addNameToExtend($line_column, $user_extend);

        $valid_list = OrderService::orderNumber($admin, CommonConstant::DEFAULT_0);
        $valid_list = array_column($valid_list, null, 'line_id');
        $expire_list = OrderService::orderNumber($admin, CommonConstant::DEFAULT_1);
        $expire_list = array_column($expire_list, null, 'line_id');
        $text_user_list = OrderService::orderNumber($admin, CommonConstant::DEFAULT_2);
        $text_user_list = array_column($text_user_list, null, 'line_id');
        $exchange_user_list = OrderService::orderNumber($admin, CommonConstant::DEFAULT_4);
        $exchange_user_list = array_column($exchange_user_list, null, 'line_id');
        $refund_list = OrderService::orderNumber($admin, CommonConstant::DEFAULT_5);
        $refund_list = array_column($refund_list, null, 'line_id');

        // 有效数量
        $valid_data = [];
        // 过期数量
        $expire_data = [];
        // 已测试数量
        $text_user_data = [];
        // 已调试数量
        $exchange_user_data = [];
        // 已退款数量
        $refund_user_data = [];
        foreach ($line_column as $value) {
            $valid_data[$value['id']] = $valid_list[$value['id']]['number'] ?? 0;
            $expire_data[$value['id']] = $expire_list[$value['id']]['number'] ?? 0;
            $text_user_data[$value['id']] = $text_user_list[$value['id']]['number'] ?? 0;
            $exchange_user_data[$value['id']] = $exchange_user_list[$value['id']]['number'] ?? 0;
            $refund_user_data[$value['id']] = $refund_list[$value['id']]->number ?? 0;
        }

        // 系统默认推广链接
        $config = OptionService::getConfig('logo');
        $link_info = UserLinkService::getDefaultUserLinkInfo($admin, $config);

        // 注册人数
        $invitation_total = Util::db()->table('wa_admins')
            ->where('invitation_id', $admin['id'])
            ->where('user_status', CommonConstant::DEFAULT_2)
            ->count('id');

        $info = $admin;
        $info['parent_user_info'] = $parent_user_info;
        $info['user_extend'] = $user_extend;
        $info['valid_data'] = $valid_data;
        $info['expire_data'] = $expire_data;
        $info['text_user_data'] = $text_user_data;
        $info['exchange_user_data'] = $exchange_user_data;
        $info['refund_user_data'] = $refund_user_data;
        $info['link_info'] = $link_info;
        $info['invitation_total'] = $invitation_total;
        unset($info['password'], $info['password_new']);
        return $info;
    }

    /**
     * 上级用户信息
     *
     * @return array
     **/
    public static function getParentUserInfo($admin){
        $invitation_id = $admin['invitation_id'] > 0 ? $admin['invitation_id'] : 1;
        $parent_user_info = Util::db()->table('wa_admins')
            ->where('id', $invitation_id)
            ->select('id','username', 'avatar', 'qq', 'weixin')
            ->first();
        if($parent_user_info->id == 1){
            $kefu = OptionService::getConfig('kefu');
            $parent_user_info->qq = $kefu['kefu_qq'];
            $parent_user_info->weixin = $kefu['kefu_weixin'];
        }
        return (array)$parent_user_info;
    }

    /**
     * 佣金统计
     *
     * @param array $admin
     **/
    public static function getCommissionCount($admin)
    {
        $commission_total = 0;
        $commission = 0;
        $withdrawal_success = 0;
        $withdrawal_failed = 0;
        $commission_month = 0;
        if($admin['user_status'] == CommonConstant::DEFAULT_2){
            $commission_total = $admin['commission_total'];
            $commission = $admin['commission'];
            $db = Util::db();
            $withdrawal_success = $db->table('wa_v1_user_withdrawal')
                ->where('user_id', $admin['id'])
                ->where('status', CommonConstant::DEFAULT_2)
                ->sum('payamount');
            $withdrawal_failed = $db->table('wa_v1_user_withdrawal')
                ->where('user_id', $admin['id'])
                ->where('status', CommonConstant::DEFAULT_1)
                ->sum('payamount');
            $start = Date::unixtime('month');
            $end = Date::unixtime('month',0,'end');
            $commission_month = $db->table('wa_v1_user_commission_log')
                ->where('user_id', $admin['id'])
                ->whereIn('type', [CommonConstant::MONEY_LOG_TYPE_0, CommonConstant::MONEY_LOG_TYPE_4, CommonConstant::MONEY_LOG_TYPE_5])
                ->whereBetween('created_at', [date('Y-m-d H:i:s',$start), date('Y-m-d H:i:s',$end)])
                ->sum('money');
        }
        return compact('admin','commission_total', 'commission', 'withdrawal_success', 'withdrawal_failed', 'commission_month');
    }

    /**
     * 搜索下级会员列表
     *
     * @param array $params
     * @param array $admin 管理员/会员
     * @param array $user 会员
     **/
    public static function getInvitationUserList($params, $admin,$user)
    {
        list($username) = array_values($params);

        $list = Util::db()->table('wa_admins')
            ->where('invitation_id', $user['id'])
            ->where('username', 'like', "%$username%")
            ->select(['id', 'username', 'ident_type'])
            ->get()
            ->toArray();
        foreach ($list as $key => $value) {
            $value->ident_type_text = $value->ident_type > CommonConstant::DEFAULT_0 ? '已认证' : '未认证';
        }
        return $list;
    }


    /**
     * 更新金额
     *
     * @param array $logData
     * @param integer $user_id 会员ID
     * @param mixed $user 会员信息
     * @param array $extend 扩展参数
     * @return mixed
     */
    public static function money($logData, $user_id, $user, $extend = [])
    {
        $money = $logData['money'];
        $changeType = $logData['change_type'];
        if (!$user) {
            $user = Admin::where('id', $user_id)->lockForUpdate()->first(['id', 'money','money_recharge']);
        }
        $logId = 0;
        if ($money > 0) {
            $moneyAfter = $changeType == CommonConstant::DEFAULT_10 ? bcadd($user['money'], $money, 2) : bcsub($user['money'], $money, 2);
            $logData['money_before'] = $user['money'];
            $logData['money_after'] = $moneyAfter;
            if (isset($extend['type']) && $extend['type'] == 'recharge') {
                $user->increment('money', $money, ['money_recharge' => $user->money_recharge + $money]);
            } else {
                doUpdate(['money' => $moneyAfter], $user);
            }

            if (isset($extend['id']) && $extend['id'] > 0) {
                V1UserMoneyLog::where('id', $extend['id'])->update($logData);
            } else {
                $logId = doInsert($logData, new V1UserMoneyLog());
            }
        } else {
            $logData['money_before'] = $user['money'];
            $logData['money_after'] = $user['money'];
            $logId = doInsert($logData, new V1UserMoneyLog());
        }
        return $logId;
    }

    /**
     * 更新佣金
     *
     * @param array $logData
     * @param integer $user_id 会员ID
     * @param mixed $user 会员信息
     * @param array $extend 扩展参数
     * @return mixed
     */
    public static function commission($logData, $user_id, $user = [], $extend = [])
    {
        $money = $logData['money'];
        $changeType = $logData['change_type'];
        if (!$user) {
            $user = Admin::where('id', $user_id)->lockForUpdate()->first(['id', 'commission','commission_total']);
        }
        $logId = 0;
        if ($money > 0) {
            $moneyAfter = $changeType == CommonConstant::DEFAULT_10 ? bcadd($user['commission'], $money, 2) : bcsub($user['commission'], $money, 2);
            $logData['money_before'] = $user['commission'];
            $logData['money_after'] = $moneyAfter;
            if (isset($extend['type']) && $extend['type'] == 'commission') {
                $user->increment('commission', $money, ['commission_total' => $user->commission_total + $money]);
            } elseif (isset($extend['type']) && $extend['type'] == 'commission_refund') {
                $user->decrement('commission', $money, ['commission_total' => $user->commission_total - $money]);
            } else {
                doUpdate(['commission' => $moneyAfter], $user);
            }

            if (isset($extend['id']) && $extend['id'] > 0) {
                V1UserCommissionLog::where('id', $extend['id'])->update($logData);
            } else {
                $logId = doInsert($logData, new V1UserCommissionLog());
            }
        } else {
            $logData['money_before'] = $user['commission'];
            $logData['money_after'] = $user['commission'];
            $logId = doInsert($logData, new V1UserCommissionLog());
        }
        return $logId;
    }

}
